import React, { memo, useState, useEffect } from "react";

import sty from "./sty.module.css";
import PropTypes from "prop-types";

import Scroll from "@/components/scroll";
let newArr = [];

const SongList = (props) => {
  const { bottomText, list, currentSongId, onSelectSong } = props;
  const [songs, setSongs] = useState([]);

  useEffect(() => {
    console.log("list onPullingUp  ");
    newArr = list;
    onPullingUp();
  }, [list]);
  useEffect(() => {
    console.log("songs", songs);
  }, [songs]);
  const hasMore = songs.length === newArr.length;
  const onPullingUp = () => {
    console.log("onPullingUp");
    console.log("newArr  ", newArr);
    const len = songs.length;
    if (len === newArr.length) {
      return;
    }
    let arr = [...newArr.slice(len, 10 + len)];
    console.log("arr", arr);
    console.log("songs", songs);
    arr = [...songs, ...arr];
    console.log("arr", arr);
    setSongs(() => arr);
  };

  return (
    <Scroll onPullingUp={onPullingUp}>
      <ul className={sty.songsList}>
        {songs.length ? (
          songs.map((v, i) => (
            <li key={v.id} onClick={() => onSelectSong(v.id)}>
              <div className={sty.index}>{i + 1}</div>
              <img src={v.al && v.al.picUrl} alt="" />
              <div className={sty.info}>
                <h3>{v.name}</h3>
                <div className={sty.desc}>
                  {v.ar &&
                    v.ar.reduce((init, item, i) => {
                      if (i < v.ar.length - 1) {
                        init += item.name + "/";
                      } else {
                        init += item.name + "-";
                      }
                      return init;
                    }, "")}
                  {v.ar.name || ""}
                </div>
              </div>
              <i
                className={
                  currentSongId === v.id
                    ? "iconfont  icon-bofang2"
                    : "iconfont  icon-bofang"
                }
              ></i>
            </li>
          ))
        ) : (
          <li className={sty.empty}>没有数据</li>
        )}
        {hasMore ? (
          <li key="empty" className={sty.empty}>
            没有数据
          </li>
        ) : (
          <li key="lastLi">{bottomText}</li>
        )}
      </ul>
    </Scroll>
  );
};

SongList.propTypes = {
  bottomText: PropTypes.string,
  list: PropTypes.array,
  currentSongId: PropTypes.number,
  onSelectSong: PropTypes.func,
};
SongList.defaultProps = {
  bottomText: "加载中...",
  list: [],
  currentSongId: 0,
  onSelectSong: () => {},
};
export default memo(SongList);
